package com.flysh.host.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.flysh.host.model.Menu;
import com.flysh.host.util.DaoUtil;

public class MenuDaoImpl implements MenuDao{

	public List<Menu> getMenusByRoleId(Long roleId) {
		List<Menu> list = new ArrayList<Menu>();
		Connection conn = DaoUtil.getConnection();
		PreparedStatement ps  = null;
		ResultSet rs = null;
		String sql = "select m.ID as id,m.NAME as name,m.URL as url,m.PID as pid from T_MENU m where m.ID in (select MENU_ID from T_ROLE_MENU where ROLE_ID = ?)";
		 try {
			ps = conn.prepareStatement(sql);
			ps.setObject(1, roleId);
			rs = ps.executeQuery();
			while(rs.next()){
				Menu menu = new Menu();
				menu.setId(rs.getLong("id"));
				menu.setMenuName(rs.getString("name"));
				menu.setUrl(rs.getString("url"));
				Long pid = rs.getLong("pid");
				menu.setPid(pid);
				list.add(menu);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DaoUtil.close(conn, ps, rs);
		}
		return list;
	}

	@Override
	public List<Menu> getMenusByPId(Long pid) {
		List<Menu> list = new ArrayList<Menu>();
		Connection conn = DaoUtil.getConnection();
		PreparedStatement ps  = null;
		ResultSet rs = null;
		String sql = "select ID as id,NAME as name,URL as url,PID as pid from T_MENU where PID=?";
		 try {
			ps = conn.prepareStatement(sql);
			ps.setObject(1, pid);
			rs = ps.executeQuery();
			while(rs.next()){
				Menu menu = new Menu();
				menu.setId(rs.getLong("id"));
				menu.setMenuName(rs.getString("name"));
				menu.setUrl(rs.getString("url"));
				menu.setPid(rs.getLong("pid"));
				list.add(menu);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DaoUtil.close(conn, ps, rs);
		}
		return list;
	}

}
